<template>
  <div class="content">
    <div class="scroll-view-box" v-loading="submitBtn">
      <div class="user-title-box">采购明细</div>
      <el-form label-width="120px" :inline="true" :model="addForm" :rules="addFormRules" ref="addFormRules"
        label-position="top">
        <el-form-item label="采购类型" prop="purchase_type">
          <el-radio-group v-model="addForm.purchase_type" class="input-width">
            <el-radio :label="1">项目采集</el-radio>
            <el-radio :label="2">售后采集</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否需要结算" prop="settle_or_not" v-if="addForm.purchase_type == 2">
          <el-radio-group v-model="addForm.settle_or_not" class="input-width">
            <el-radio :label="1">需要</el-radio>
            <el-radio :label="2">不需要</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="采购项目" prop="project_id" v-if="addForm.purchase_type == 1">
          <el-select filterable v-model="addForm.project_id" placeholder="选择采购项目" clearable class="input-width">
            <el-option v-for="item in projectList" :key="item.id" :label="item.project_name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购供应商" prop="supplier_id">
          <el-select filterable @change="supplierChangeFunc" v-model="addForm.supplier_id" placeholder="选择采购供应商" clearable
            class="input-width">
            <el-option v-for="item in supplierList" :key="item.Id" :label="item.supplier_name" :value="item.Id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品规格" prop="product_specs_id">
          <el-select filterable :disabled="!productSpecsList.length" @change="productSpecsChangeFunc"
            v-model="addForm.product_specs_id" placeholder="选择产品规格(先选择供应商)" clearable class="input-width">
            <el-option v-for="item in productSpecsList" :key="item.id" :label="item.product_specs_name"
              :value="item.product_specs_id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品类型" prop="insurance_status">
          <el-select filterable disabled v-model="addForm.insurance_status" placeholder="选择产品类型" clearable class="input-width">
            <el-option label="保险类" :value="1">
            </el-option>
            <el-option label="非保险类" :value="2">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品大类" prop="product_type_id">
          <el-select filterable disabled v-model="addForm.product_type_id" placeholder="选择产品大类" clearable class="input-width">
            <el-option v-for="item in productTypeList" :key="item.Id" :label="item.product_type_name" :value="item.Id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单数量" prop="num">
          <el-input @change="numChangeFunc" v-input-limit="2" v-model="addForm.num" placeholder="输入下单数量" clearable
            class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="采购单价" prop="unit_price">
          <el-input disabled v-input-limit="2" v-model="addForm.unit_price" placeholder="输入采购单价" clearable
            class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="采购总价" prop="total_price">
          <el-input disabled v-input-limit="2" v-model="addForm.total_price" placeholder="输入采购总价" clearable
            class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="售后单" prop="after_sales_id" v-if="addForm.purchase_type == 2">
          <el-select filterable @change="aftersalesChangeFunc" v-model="addForm.after_sales_id" placeholder="选择售后单" clearable
            class="input-width">
            <el-option v-for="item in afterSalesList" :key="item.id" :label="`${item.after_sales_number}`"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单日期" prop="order_time">
          <el-date-picker value-format="yyyy-MM-dd" v-model="addForm.order_time" type="date" placeholder="选择下单日期"
            class="input-width">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="期望到货日期" prop="arrival_time">
          <el-date-picker value-format="yyyy-MM-dd" v-model="addForm.arrival_time" type="date" placeholder="选择期望到货日期"
            class="input-width">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="addForm.notes" placeholder="输入备注" clearable class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="保险合同" prop="file_list" v-if="addForm.insurance_status == 1">
          <div class="file-list-box">
            <el-upload accept=".zip,.ppt,.ppsx,.pptx,pdf" multiple class="avatar-uploader" action="#"
              :show-file-list="false" :auto-upload="false" list-type="picture-card" :on-change="change_file">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="file-item-box" v-for="(item, index) in addForm.file_list" :key="index">
              <div class="el-icon-delete-box" @click="delFileFunc(index)">
                <i class="el-icon-error"></i>
              </div>
              <el-tooltip class="item" effect="dark" :content="item.name || item.file_name" placement="top">
                <img class="img" :src="$fileImgFunc(item)" @click="$fileViewHandle(item)" />
              </el-tooltip>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveSubmit('addFormRules')" :loading="submitBtn">提交</el-button>
        <el-button @click="cancelFunc">关闭</el-button>
      </span>
    </div>
  </div>
</template>
<script>
import projectApi from "@/api/projectApi";
import purchaseApi from "@/api/purchaseApi";
import commonApi from "@/api/common";
import * as math from "mathjs";
var fileListRule = (rule, value, callback) => {
  if (!value.length) {
    return callback(new Error("请选择保险合同文件"));
  } else {
    callback();
  }
};
export default {
  name: 'addPurchase',
  data() {
    return {
      addForm: {
        purchase_type: 1,
        settle_or_not: 1,//是否需要结算
        project_id: "",
        supplier_id: "",
        product_specs_id: "",
        insurance_status: "",
        product_type_id: "",
        num: "",
        unit_price: "",
        total_price: "",
        after_sales_id: "",
        arrival_time: "",
        notes: "",
        order_time: "",
        file_list: [],
      },
      addFormRules: {
        purchase_type: [
          {
            required: true,
            message: "请选择订单类型",
            trigger: "change",
          },
        ],
        project_id: [
          {
            required: true,
            message: "请选择采购项目",
            trigger: "change",
          },
        ],
        supplier_id: [
          {
            required: true,
            message: "请选择供应商",
            trigger: "change",
          },
        ],
        product_specs_id: [
          {
            required: true,
            message: "请选择产品规格",
            trigger: "change",
          },
        ],
        insurance_status: [
          {
            required: true,
            message: "请选择产品类型",
            trigger: "change",
          },
        ],
        product_type_id: [
          {
            required: true,
            message: "请选择产品大类",
            trigger: "change",
          },
        ],
        num: [
          {
            required: true,
            message: "请输入产品数量",
            trigger: "change",
          },
        ],
        unit_price: [
          {
            required: true,
            message: "请输入采购单价",
            trigger: "change",
          },
        ],
        total_price: [
          {
            required: true,
            message: "请输入采购总价",
            trigger: "change",
          },
        ],
        after_sales_id: [
          {
            required: true,
            message: "请选择售后单",
            trigger: "change",
          },
        ],
        arrival_time: [
          {
            required: true,
            message: "请选择期望到货时间",
            trigger: "change",
          },
        ],
        order_time: [
          {
            required: true,
            message: "请选择期下单时间",
            trigger: "change",
          },
        ],
        file_list: [
          {
            required: true,
            validator: fileListRule,
            trigger: "change",
          },
        ],
      },
      submitBtn: false,
      objectList: [],
      afterSalesList: [],//售后列表
      productSizeList: [],
      projectList: [],//项目列表
      supplierList: [],//供应商列表
      productSpecsList: [],//产品规格
      productTypeList: [],//产品大类
    };
  },
  computed: {
    hisList() {
      return this.$store.getters.routerHis;
    },
    path() {
      return this.$route.path;
    },
  },
  mounted() {
    this.getProjectList();//项目列表
    this.getSupplier();//供应商列表
    // this.getProductSpecs();//产品规格
    this.getProductType();//产品大类
    this.optionalAfterSalesList();//售后列表

    this.getPurchaseInfo();//采购单详情
  },
  methods: {
    optionalAfterSalesList() {
      commonApi.optionalAfterSalesList().then(res => {
        console.log(res, "售后列表")
        this.afterSalesList = res.data;
      })
    },
    // ------------------------产品大类-----------------------------------
    getProductType() {
      purchaseApi.getProductType({
        page: 1,
        num: 999
      }).then(res => {
        console.log(res, "产品大类")
        if (res.code == 200) {
          this.productTypeList = res.data.list;
        }
      })
    },
    // ------------------------产品规格-----------------------------------
    getProductSpecs() {
      purchaseApi.getProductSpecs({
        page: 1,
        num: 999
      }).then(res => {
        console.log(res, "产品规格")
        if (res.code == 200) {
          this.productSpecsList = res.data.list;
        }
      })
    },
    // ------------------------供应商列表-----------------------------------
    getSupplier() {
      purchaseApi.getSupplier({
        page: 1,
        num: 999
      }).then(res => {
        console.log(res, "供应商列表")
        if (res.code == 200) {
          this.supplierList = res.data.list;
        }
      })
    },
    // ------------------------项目列表-----------------------------------
    getProjectList() {
      projectApi.getProjectList({
        page: 1,
        num: 999
      }).then(res => {
        console.log(res, "项目列表")
        if (res.code == 200) {
          this.projectList = res.data.list;
        }
      })
    },
    // ------------------------选择保险合同文件-----------------------------------
    change_file(file) {
      this.addForm.file_list.push(file);
    },
    // ------------------------删除保险合同文件-----------------------------------
    delFileFunc(index) {
      if (this.addForm.file_list[index].Id) {
        !this.addForm.delete_files ? this.addForm.delete_files = [] : "";
        this.addForm.delete_files.push(this.addForm.file_list[index].Id);
      }
      this.$nextTick(() => {
        this.addForm.file_list.splice(index, 1);
      })
    },
    // 提交
    saveSubmit(formName) {
      let addForm = this.addForm;
      console.log(addForm)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let formdata = new FormData();
          let obj = {
            purchase_type: addForm.purchase_type,
            settle_or_not: addForm.settle_or_not,
            project_id: addForm.project_id,
            supplier_id: addForm.supplier_id,
            product_specs_id: addForm.product_specs_id,
            insurance_status: addForm.insurance_status,
            product_type_id: addForm.product_type_id,
            num: addForm.num,
            unit_price: addForm.unit_price,
            total_price: addForm.total_price,
            after_sales_id: addForm.after_sales_id,
            arrival_time: addForm.arrival_time,
            notes: addForm.notes,
            order_time: addForm.order_time,
          }
          if (addForm.file_list.length) {
            addForm.file_list.forEach(item => {
              if (item.raw) {
                formdata.append('file_list[]', item.raw);
              }
            })
          }
          if (addForm.Id) {
            console.log("更新")
            obj.purchase_id = addForm.Id;
            obj.delete_files = addForm.delete_files;
            formdata.append('data', JSON.stringify(obj))
            // 修改为无需结算时候
            if (addForm.settle_or_not == 2) {
              this.checkPurchaseInSettlement({
                purchase_id: addForm.Id,
                formdata
              }, () => {
                this.updatePurchase(formdata);
              })
              return;
            }
            this.updatePurchase(formdata);
            return;
          }
          formdata.append('data', JSON.stringify(obj))
          this.addPurchase(formdata);
        } else {
          return false;
        }
      });
    },
    // 验证采购订单是否被添加结算
    checkPurchaseInSettlement(obj, cb) {
      purchaseApi.checkPurchaseInSettlement(obj).then(res => {
        console.log(res, "验证采购订单")
        if (res.code == 200) {
          // 存在结算
          if (res.data.status == 2) {
            this.$confirm('当前采购订单已生成采购结算单，修改为“无需结算”此采购订单将自动从结算单移除。是否提交修改？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.updatePurchase(obj.formdata);
            }).catch(() => {
            });
          } else {
            cb && cb()
          }
        }
      })
    },
    // ------------------------更新采购单-----------------------------------
    updatePurchase(obj) {
      this.submitBtn = true;
      purchaseApi.updatePurchase(obj).then(res => {
        console.log(res, "更新采购单")
        this.submitBtn = false;
        if (res.code == 200) {
          this.cancelFunc();
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      })
    },
    // ------------------------添加采购单-----------------------------------
    addPurchase(obj) {
      this.submitBtn = true;
      purchaseApi.addPurchase(obj).then(res => {
        console.log(res, "添加采购单")
        this.submitBtn = false;
        if (res.code == 200) {
          this.cancelFunc();
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      })
    },
    // ------------------------选择售后单（同时关联售后单的项目）-----------------------------------
    aftersalesChangeFunc(e) {
      console.log(e)
      if (!e) {
        this.addForm.project_id = '';
        return;
      }
      let afterSalesList = this.afterSalesList;
      let index = afterSalesList.findIndex(item => {
        return item.id == e;
      })
      this.addForm.project_id = afterSalesList[index].project_id;
    },
    // ------------------------采购单详情-----------------------------------
    getPurchaseInfo() {
      if (!this.$route.query.id) return;
      purchaseApi.getPurchaseInfo({
        purchase_id: this.$route.query.id
      }).then(res => {
        console.log(res, '采购单详情')
        if (res.code == 200) {
          this.addForm = res.data;
          this.getPurchaseSpecsBySupplier(this.addForm.supplier_id);
        }
      })
    },
    // 取消
    cancelFunc() {
      this.$goBackTab(this);
    },
    // 根据供应商id获取产品规格列表
    getPurchaseSpecsBySupplier(supplier_id) {
      purchaseApi.getPurchaseSpecsBySupplier({
        supplier_id
      }).then(res => {
        console.log(res, "根据供应商id获取产品规格列表")
        if (res.code == 200) {
          this.productSpecsList = res.data;
        }
      })
    },
    // 选择供应商  
    supplierChangeFunc(e) {
      if (!e) return;

      this.productSpecsList = [];
      this.addForm.product_specs_id = '';
      this.addForm.insurance_status = '';
      this.addForm.product_type_id = '';
      this.addForm.unit_price = '';
      this.getPurchaseSpecsBySupplier(e);
    },
    // 选择产品规格
    productSpecsChangeFunc(e) {
      if (!e) {
        this.addForm.insurance_status = '';
        this.addForm.product_type_id = '';
        this.addForm.unit_price = '';
        this.$nextTick(() => {
          this.numChangeFunc();
        })
        return;
      }
      let productSpecsList = this.productSpecsList;
      let index = productSpecsList.findIndex(item => {
        return item.product_specs_id == e;
      })
      this.addForm.insurance_status = productSpecsList[index].insurance_status;
      this.addForm.product_type_id = productSpecsList[index].product_type_id;
      this.addForm.unit_price = productSpecsList[index].unit_price_tax;
      this.$nextTick(() => {
        this.numChangeFunc();
      })
    },
    // 下单数量输入
    numChangeFunc() {
      console.log(this.addForm.num, this.addForm.unit_price)
      let total_price = '';
      if (this.addForm.num && this.addForm.unit_price) {
        total_price = math.format(
          math.multiply(
            math.bignumber(this.addForm.num),
            math.bignumber(this.addForm.unit_price)
          )
        );
        this.addForm.total_price = Number(total_price).toFixed(2);
      } else {
        this.addForm.total_price = Number(total_price).toFixed(2);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
@import "@/styles/addPage.scss";
</style>